<?php

namespace App\Http\Controllers\Personnel;

use App\Criteria\Personnel\Department\DepartmentBaseQueryCriteria;
use App\Http\Controllers\Controller;
use App\Http\Controllers\CurlRecordMethod;
use App\Http\Requests\Personnel\DepartmentBaseRequest;
use App\Libs\Tools\ZTree;
use App\Repositories\Personnel\DepartmentRepository;
use App\Repositories\System\UserRepository;
use App\Validators\Personnel\DepartmentValidator;
use Illuminate\Support\Facades\Input;
use Prettus\Validator\Exceptions\ValidatorException;


class DepartmentsController extends Controller
{

    use CurlRecordMethod;

    protected $index_page='personnel.department.departmentMain';
    protected $add_page='personnel.department.departmentAdd';
    protected $edit_page='personnel.department.departmentEdit';

    protected $repository;
    protected $validator;
    protected $request;
    protected $userRepository;
    public function __construct(DepartmentRepository $repository,
                                UserRepository $userRepository,
                                DepartmentValidator $validator,
                                DepartmentBaseRequest $request){
        $this->repository = $repository;
        $this->validator  = $validator;
        $this->request    = $request;
        $this->userRepository=$userRepository;
    }

    public function getBaseQueryCriteria(){
        return new DepartmentBaseQueryCriteria;
    }

    public function list_tree_data(){
        $allDepartment=$this->repository->all();
        $tree_data=ZTree::convert_department_transform_to_tree($allDepartment);
        return response()->json($tree_data);
    }

    public function delete_data(){
        try {
            $this->validator->with(Input::all())->passesOrFail('DELETE');
            $this->repository->deleteByPrimaryKeys(Input::get('id'));
            return $this->return_json_success();
        } catch (ValidatorException $e) {
            return $this->return_json_error($e);
        }
    }

    protected function get_add_data(){
        $users=$this->userRepository->all();
        $departments=$this->repository->all();
        $parent_id=Input::get('parent_id');
        return view($this->add_page,compact('users','departments','parent_id'));
    }

    protected function get_edit_data(){
        $id=$this->request->get('id');
        $users=$this->userRepository->all();
        $departments=$this->repository->findWhere([['id','<>',$id]]);
        $editEntity = $this->repository->find($id);
        return view($this->edit_page,compact('editEntity','users','departments'));
    }

}
